package model

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
)

// Product 产品模型
type Product struct {
	BaseModel
	Name        string     `json:"name" gorm:"size:100;not null"`
	Description string     `json:"description" gorm:"type:text"`
	Price       float64    `json:"price" gorm:"type:decimal(10,2);not null"`
	Stock       int        `json:"stock" gorm:"not null;default:0"`
	Images      Images     `json:"images" gorm:"type:json"`
	Attributes  Attributes `json:"attributes" gorm:"type:json"`
	CategoryID  uint       `json:"category_id" gorm:"not null"`
	Status      int        `json:"status" gorm:"default:1"`
	IsHot       bool       `json:"is_hot" gorm:"default:false"`
	IsNew       bool       `json:"is_new" gorm:"default:false"`
	IsRecommend bool       `json:"is_recommend" gorm:"default:false"`
	SalesCount  int        `json:"sales_count" gorm:"default:0"`
	ViewCount   int        `json:"view_count" gorm:"default:0"`
}

// TableName 表名
func (Product) TableName() string {
	return "products"
}

// Images 产品图片
type Images []string

// Scan 实现 sql.Scanner 接口
func (i *Images) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("failed to unmarshal Images value")
	}

	return json.Unmarshal(bytes, i)
}

// Value 实现 driver.Valuer 接口
func (i Images) Value() (driver.Value, error) {
	if i == nil {
		return nil, nil
	}
	return json.Marshal(i)
}

// Attributes 产品属性
type Attributes map[string]interface{}

// Scan 实现 sql.Scanner 接口
func (a *Attributes) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("failed to unmarshal Attributes value")
	}

	return json.Unmarshal(bytes, a)
}

// Value 实现 driver.Valuer 接口
func (a Attributes) Value() (driver.Value, error) {
	if a == nil {
		return nil, nil
	}
	return json.Marshal(a)
}

// Category 产品分类
type Category struct {
	BaseModel
	Name        string `json:"name" gorm:"size:50;not null"`
	Description string `json:"description" gorm:"size:255"`
	ParentID    uint   `json:"parent_id" gorm:"default:0"`
	Level       int    `json:"level" gorm:"default:1"`
	Sort        int    `json:"sort" gorm:"default:0"`
	Status      int    `json:"status" gorm:"default:1"`
}

// TableName 表名
func (Category) TableName() string {
	return "categories"
}
